<template>
  <div class="return-top" v-if="btnFlag" @click="backTop">
    <a href="#">
      <img
        src="https://p1.meituan.net/scarlett/87654d5e4e5e057206969c3abb8e09f33151.png"
      />
      <div>返回顶部</div>
    </a>
  </div>
</template>

<script>
export default {
  name: "Return",
  data(){
    return{
      btnFlag:false
    }
  },
  // vue的两个生命钩子，这里不多解释。
  // window对象，所有浏览器都支持window对象。它表示浏览器窗口，监听滚动事件
  mounted() {
    window.addEventListener("scroll", this.scrollToTop);
  },
  destroyed() {
    window.removeEventListener("scroll", this.scrollToTop);
  },

  methods: {
    // 点击图片回到顶部方法，加计时器是为了过渡顺滑
    backTop() {
      const that = this;
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          that.scrollTop + ispeed;
        if (that.scrollTop === 0) {
          clearInterval(timer);
        }
      }, 16);
    },

    // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop() {
      const that = this;
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      that.scrollTop = scrollTop;
      if (that.scrollTop > 60) {
        that.btnFlag = true;
      } else {
        that.btnFlag = false;
      }
    },
  },
};
</script>

<style scoped>
.return-top {
  position: fixed;
  right: 0;
  bottom: 125px;
  z-index: 1;
}
.return-top a {
  text-decoration: none;
  background-image: linear-gradient(134deg, #fb3333, #ff5269 75%);
  width: 110px;
  height: 38px;
  display: flex;
  justify-content: center;
  border-radius: 19px 0 0 19px;
  align-items: center;
  font-size: 14px;
  color: white;
}
.return-top a img {
  width: 23px;
  height: 23px;
  padding-right: 5px;
}
</style>
